//
//  LZTTabBar.swift
//  LZTWeibo
//
//  Created by Yin jianxun on 16/8/10.
//  Copyright © 2016年 YinJianxun. All rights reserved.
//

import UIKit

//代理 让MainVc进行推出点击事件对应的跳转
protocol LZTTabBarDelegate:NSObjectProtocol{
    // 声明方法
    func tabBarButtonClick()
}

class LZTTabBar: UITabBar {
    
    //声明一个代理
    weak var lztDelegate: LZTTabBarDelegate?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    //断言
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //监听方法：撰写按钮的点击事件
    func buttonClick() {
     
        //
        lztDelegate?.tabBarButtonClick()
    }
    
    //MAEK: - 设置试图
    private func setupUI() {
        
        addSubview(composeBtuton)
    }
    
    //调整 撰写按钮的位置 frame
    override func layoutSubviews() {
        
        //继承父类 布局
        super.layoutSubviews()
        
        let childW = self.frame.width * 0.2
        var index: CGFloat = 0
        
        //修改各个 tabBarButton的位置
        for value in self.subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                //设置各个按钮的 x width
                value.frame.size.width = childW
                value.frame.origin.x = childW * index
                
                index++
                //第三个按钮需要再加上一个1，因为有一个撰写按钮
                if index == 2 {
                    index++
                }
            }
        }
        
        //不可以设置约束  可以修正frame
        composeBtuton.center.x = self.frame.width * 0.5
        composeBtuton.center.y = self.frame.height * 0.5
        
    }
    
    
    //懒加载 撰写按钮控件
    private lazy var composeBtuton: UIButton = {
        
        let button = UIButton()
        //点击事件
        button.addTarget(self, action: #selector(LZTTabBar.buttonClick), forControlEvents: .TouchUpInside)
        
        //设置 背景Image
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        //设置 Image
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        //按钮自适应
        button.sizeToFit()
        
        return button
        
    }()
}
